package com.glacier.cloud.gateway.filter.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.support.GatewayToStringStyler;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * date 2024-01-31 17:10
 * 自定义过滤器
 * 参照 AddResponseHeaderGatewayFilterFactory
 *
 * @author glacier
 * @version 1.0
 */
@Slf4j
public class GlacierGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    public GlacierGatewayFilterFactory() {
    }

    @Override
    public GatewayFilter apply(final AbstractNameValueGatewayFilterFactory.NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    GlacierGatewayFilterFactory.this.addHeader(exchange, config);
                }));
            }

            @Override
            public String toString() {
                return GatewayToStringStyler.filterToStringCreator(GlacierGatewayFilterFactory.this).append(config.getName(), config.getValue()).toString();
            }
        };
    }

    void addHeader(ServerWebExchange exchange, AbstractNameValueGatewayFilterFactory.NameValueConfig config) {
        String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
        HttpHeaders headers = exchange.getResponse().getHeaders();
        if (!exchange.getResponse().isCommitted()) {
            headers.add(config.getName(), value);
        }

    }
}
